package com.zzh.partnersys.im.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.google.gson.Gson;
import com.zzh.partnersys.im.message.request.ChatEmojiRequestMessage;
import com.zzh.partnersys.im.rocketmq.contant.MQConstant;
import com.zzh.partnersys.im.rocketmq.producer.MessageSender;
import com.zzh.partnersys.im.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @author ??????
 * @version 1.0
 */
@Sharable
public class ChatEmojiRequestMessageHandler extends SimpleChannelInboundHandler<ChatEmojiRequestMessage> {
    Gson gson = new Gson();

    private MessageSender messageSender;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatEmojiRequestMessage chatEmojiRequestMessage) throws Exception {
        System.out.println("chatEmojiRequestMessage"+ chatEmojiRequestMessage);
        //???????????????????
        if (chatEmojiRequestMessage == null){

        }
        //??????????????
        Long toUid = chatEmojiRequestMessage.getUid();//???????????

        //????????????todo ????????????��???????/redis??
        Channel channel = SessionFactory.getSession().getChannel(toUid);
        if (channel != null){
            System.out.println("????");
            //???TextWebSocketFrame??????��????WebSocket)
            String json = gson.toJson(chatEmojiRequestMessage);
            channel.writeAndFlush(new TextWebSocketFrame(json));
        }

        //rocketMQ????????
        if (messageSender == null){
            messageSender = getMessageSender();
        }
        messageSender.sendMsg(MQConstant.CHAT_ONE_EMOTION_TOPIC,chatEmojiRequestMessage);
    }

    protected MessageSender getMessageSender(){
        return SpringUtil.getBean(MessageSender.class);
    }

}
